<template>
  <div class="card" style="width: 60%; padding: 30px; margin: auto">
    <h3 style="text-align: center; margin-bottom: 20px">学校信息</h3>

    <el-form ref="formRef" :model="School.form" :rules="School.rules" label-width="120px">

      <!-- 账号 -->
      <el-form-item label="账号">
        <el-input v-model="School.form.username" disabled />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="School.form.password" placeholder="请输入密码" :disabled="!isEditing" />
      </el-form-item>
      <!-- 学校名称 -->
      <el-form-item label="学校名称" prop="schoolName">
        <el-input v-model="School.form.schoolName" placeholder="请输入学校名称" :disabled="!isEditing" />
      </el-form-item>

      <!-- 地址 -->
      <el-form-item label="地址" prop="address">
        <el-input v-model="School.form.address" placeholder="请输入地址" :disabled="!isEditing" />
      </el-form-item>

      <!-- 联系电话 -->
      <el-form-item label="联系电话" prop="contactNumber">
        <el-input v-model="School.form.contactNumber" placeholder="请输入联系电话" :disabled="!isEditing" />
      </el-form-item>

      <!-- 校长 -->
      <el-form-item label="校长" prop="principal">
        <el-input v-model="School.form.principal" placeholder="请输入校长姓名" :disabled="!isEditing" />
      </el-form-item>

      <!-- 建校年份 -->
      <el-form-item label="建校年份" prop="establishedYear">
        <el-input-number v-model="School.form.establishedYear" :min="0" placeholder="请输入建校年份" :disabled="!isEditing" />
      </el-form-item>
          <el-form-item label="上传文件">
        <div class="upload-container" :class="{'has-file': hasFileUploaded}">
          <el-upload 
            ref="uploadRef"
            class="custom-upload" 
            action="" 
            :auto-upload="false" 
            :on-change="handleFileChange"
            :show-file-list="false" 
            accept=".doc,.docx" 
            :limit="1"
            drag
          >
            <div class="upload-area" @click="triggerUpload">
          
              <div class="close-btn" v-if="hasFileUploaded" @click.stop="clearFile">
                <el-icon><Close /></el-icon>
              </div>
              
              <el-icon class="upload-icon"><UploadFilled /></el-icon>
              <p class="upload-text">点击上传，或将文件拖拽到此处</p>
              <p class="upload-tip">仅支持上传.docx 格式文件</p>
              
              <!-- 文件信息 -->
              <div class="file-info" v-if="hasFileUploaded">
                <el-icon class="success-icon"><SuccessFilled /></el-icon>
                <span class="file-name">{{ fileName }}</span>
              </div>
            </div>
            <template #tip>
              <div class="upload-action">
                <el-button type="primary" class="upload-btn" @click="triggerUpload">开始上传</el-button>
              </div>
            </template>
          </el-upload>
        </div>
      </el-form-item>
      
      <!-- 上传后才显示的按钮 -->
      <div class="preview-toggle" v-if="hasFileUploaded">
        <el-button @click="isPreviewVisible = !isPreviewVisible" :type="isPreviewVisible ? 'primary' : 'info'"
          :icon="isPreviewVisible ? Minus : Plus" circle />
      </div>
      <!-- 预览内容区域 -->
      <transition name="fade">
        <div v-show="isPreviewVisible" class="preview-container">
          <div class="preview-content" v-if="previewContent">
            <h4 style="color: #606266; margin-top: 0;">简历内容预览：</h4>
            <div class="preview-body" v-html="previewContent"></div>
          </div>
          <div v-else class="preview-content">
            <p style="text-align: center; color: #999;">请上传 .docx 格式文件以查看预览内容</p>
          </div>
        </div>
      </transition>

      <!-- 描述 -->
      <el-form-item label="描述" prop="description">
        <el-input v-model="School.form.description" type="textarea" :rows="3" placeholder="请输入学校描述"
          :disabled="!isEditing" />
      </el-form-item>

      <!-- 创建时间 -->
      <el-form-item label="创建时间">
        <el-input v-model="School.form.createdAt" disabled />
      </el-form-item>

      <!-- 最后更新时间 -->
      <el-form-item label="最后更新时间">
        <el-input v-model="School.form.updatedAt" disabled />
      </el-form-item>

      <!-- 按钮区域 -->
      <el-form-item style="text-align: center">
        <el-button @click="toggleEdit" type="primary" v-if="!isEditing">修改信息</el-button>
        <el-button @click="updateSchool" type="success" v-else>提交信息</el-button>
        <el-button @click="router.back()" plain>返回</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>

<script setup>

import { Plus, Minus } from '@element-plus/icons-vue'
import { reactive, ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { parseJwt, getToken } from '@/utils/auth'
import * as mammoth from 'mammoth' // 导入 mammoth.js
const previewContent = ref('')
const formRef = ref()
const isPreviewVisible = ref(false) // 控制是否显示预览
// 添加上传组件的引用
const uploadRef = ref(null)
// 添加文件名引用
const fileName = ref('')
const hasFileUploaded = ref(false) // 控制按钮显示状态

// 清空文件的方法
const clearFile = () => {
  // 重置上传组件
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
  
  // 重置状态
  hasFileUploaded.value = false
  fileName.value = ''
  previewContent.value = ''
  isPreviewVisible.value = false
  
  // 清除预览内容
  ElMessage.success('已清除上传的简历，可以重新上传')
}
const triggerUpload = () => {
  if (uploadRef.value) {
    uploadRef.value.$el.querySelector('input[type="file"]').click()
  }
}
const School = reactive({
  form: {
    username: '',
    password: '',
    schoolName: '',
    address: '',
    contactNumber: '',
    principal: '',
    establishedYear: null,
    description: '',
    createdAt: '',
    updatedAt: ''
  },
  rules: {
    username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    schoolName: [{ required: true, message: '请输入学校名称', trigger: 'blur' }],
    address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
    contactNumber: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
    principal: [{ required: true, message: '请输入校长姓名', trigger: 'blur' }],
    establishedYear: [{ required: true, message: '请输入建校年份', trigger: 'blur' }],
    description: [{ required: true, message: '请输入学校描述', trigger: 'blur' }]
  }
})

const isEditing = ref(false)

// 模拟从 JWT 解析用户信息并加载数据
const loadSchoolInfo = () => {
  const token = getToken();
  if (!token) {
    ElMessage.error('请先登录');
    router.push('/login');
    return;
  }

  const userInfo = parseJwt(token);
  if (!userInfo || !userInfo.id) {
    ElMessage.error('用户信息异常，请重新登录');
    router.push('/login');
    return;
  }

  axios.get(`/api/school/info/${userInfo.id}`, {
    headers: {
      Authorization: 'Bearer ' + token
    }
  }).then(res => {
    if (res.status === 304) {
      const cachedData = JSON.parse(localStorage.getItem('cachedSchoolData'));
      if (cachedData) {
        populateForm(cachedData);
      } else {
        ElMessage.error('缓存数据缺失，请刷新页面');
      }
    } else if (res.data && res.data.code === 200 && res.data.data) {
      populateForm(res.data.data);
      localStorage.setItem('cachedSchoolData', JSON.stringify(res.data.data));
    } else {
      ElMessage.error('获取用户信息失败');
    }
  }).catch(err => {
    console.error('请求失败:', err);
    ElMessage.error('网络异常，请重试');
  });
};


const populateForm = (data) => {
  School.form.username = data.username
  School.form.password = data.password
  School.form.schoolName = data.schoolName
  School.form.address = data.address
  School.form.contactNumber = data.contactNumber
  School.form.principal = data.principal
  School.form.establishedYear = data.establishedYear
  School.form.description = data.description
  School.form.createdAt = formatDate(data.createdAt)
  School.form.updatedAt = formatDate(data.updatedAt)
}

// 格式化日期函数
const formatDate = (dateStr) => {
  if (dateStr == null) return ''
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 切换编辑状态
const toggleEdit = () => {
  isEditing.value = !isEditing.value
}

// 更新学校信息
const updateSchool = async () => {
  const userInfo = parseJwt()
  if (!userInfo || !userInfo.id) {
    ElMessage.error('用户信息异常，请重新登录')
    router.push('/login')
    return
  }

  const dataToSend = {
    id: userInfo.id,
    username: School.form.username,
    password: School.form.password,
    schoolName: School.form.schoolName,
    address: School.form.address,
    contactNumber: School.form.contactNumber,
    principal: School.form.principal,
    establishedYear: School.form.establishedYear,
    description: School.form.description
  }

  try {
    const res = await axios.put('/api/school/update', dataToSend, {
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    })

    if (res.data.code === 200) {
      ElMessage.success('更新成功')
      localStorage.setItem('school', JSON.stringify(School.form))
      toggleEdit() // 返回只读模式
    } else {
      ElMessage.error(res.data.msg || '更新失败')
    }
  } catch (error) {
    console.error('请求错误:', error)
    if (error.response?.status === 401) {
      ElMessage.error('登录状态异常，请重新登录')
      router.push('/login')
    } else {
      ElMessage.error('网络异常，请重试')
    }
  }
}
// 上传简历并解析
// 上传简历并解析
const handleFileChange = async (file) => {
  if (!file.raw) return;

  // 检查文件类型
  const isWordFile = file.raw.type === 'application/msword' || 
                     file.raw.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
                     file.name.endsWith('.doc') || 
                     file.name.endsWith('.docx');

  if (!isWordFile) {
    ElMessage.error('请上传Word文档(.doc或.docx)');
    return;
  }

  // .docx 文件预览处理
  if (file.name.endsWith('.docx')) {
    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        const arrayBuffer = e.target.result;
        const result = await mammoth.convertToHtml({ arrayBuffer });
        previewContent.value = result.value; // 提取 HTML 内容
      } catch (err) {
        console.error('预览解析失败:', err);
        previewContent.value = '<p>无法解析文档，请检查文件格式</p>';
      }
    };
    reader.readAsArrayBuffer(file.raw);
  } else {
    previewContent.value = '<p>仅支持 .docx 格式预览</p>';
  }
fileName.value = file.name
  // 构造表单数据
  const formData = new FormData();
  formData.append('file', file.raw);

  // 上传文件并获取解析结果
  axios.post('/api/doc/upload/school', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
      Authorization: 'Bearer ' + getToken()
    }
  })
  .then(response => {
    console.log('上传成功:', response.data);
    if (response.data.success) {
      hasFileUploaded.value = true;
      const resumeData = response.data.data;

      // 直接赋值（字段名已知且规范）
      
      School.form.schoolName = resumeData.schoolName || '';
      School.form.address = resumeData.address || '';
      School.form.contactNumber = resumeData.contactNumber || '';
      School.form.principal = resumeData.principal || '';

      // 建校年份字段：尝试转换为数字
      if (resumeData.establishedYear) {
        const yearNum = parseInt(resumeData.establishedYear, 10);
        School.form.establishedYear = isNaN(yearNum) ? null : yearNum;
      } else {
        School.form.establishedYear = null;
      }

      School.form.description = resumeData.description || '';

      // 切换到编辑模式
      if (!isEditing.value) {
        isEditing.value = true;
      }

      ElMessage.success('简历信息已自动填充');
    } else {
      ElMessage.error('解析失败: ' + response.data.message);
    }
  })
  .catch(error => {
    console.error('上传失败:', error);
    ElMessage.error('简历解析失败，请重试');
  });
};
  
onMounted(() => {
  loadSchoolInfo()
})
</script>
<style scoped>
/* 按钮样式 */
.preview-toggle {
  text-align: center;
  margin: 15px 0;
}

.preview-toggle .el-button {
  width: 40px;
  height: 40px;
  font-size: 20px;
  border-radius: 50%;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* 预览容器 */
.preview-container {
  background: #f9fafc;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 15px;
  max-height: 400px;
  overflow-y: auto;
  transition: all 0.3s ease;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 动画效果 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

.upload-area {
  text-align: center;
  padding: 20px;
}

.upload-icon {
  font-size: 40px;
  color: #409eff;
  margin-bottom: 10px;
}

.upload-text {
  font-size: 14px;
  color: #606266;
  margin: 5px 0;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin: 5px 0;
}

.upload-action {
  margin-top: 15px;
  text-align: center;
}

.upload-btn {
  width: 120px;
}
/* 关闭按钮 - 修复定位 */
.close-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #f56c6c;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background-color: #f78989;
  transform: scale(1.1);
}

/* 文件信息样式 */
.file-info {
  margin-top: 15px;
  padding: 8px;
  background-color: #f0f9eb;
  border-radius: 4px;
  display: flex;
  align-items: center;
  width: 80%;
  justify-content: center;
}

.success-icon {
  color: #67c23a;
  margin-right: 8px;
}

.file-name {
  font-size: 14px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 有文件时修改样式 */
.has-file .el-upload-dragger {
  background-color: #f5f7fa;
  border-color: #e1f3d8;
}

/* 预览区域样式 */
.preview-toggle {
  text-align: center;
  margin: 15px 0;
  transition: opacity 0.3s ease;
}

.preview-toggle .el-button {
  width: 40px;
  height: 40px;
  font-size: 20px;
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.preview-container {
  background: #f9fafc;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 15px;
  max-height: 400px;
  overflow-y: auto;
  transition: all 0.3s ease;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

.preview-content {
  font-size: 14px;
  line-height: 1.6;
  color: #303133;
  word-break: break-all;
}

.preview-body {
  padding-left: 10px;
  border-left: 2px solid #e4e7ed;
}
</style>